package com.dingup.homework.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.homework.bean.DO.HwSsatWordDO;
import com.dingup.homework.bean.DO.HwSsatWordRecordDO;
import com.dingup.homework.service.HwHomeworkRecordsService;
import com.dingup.homework.service.HwSsatWordRecordService;
import com.dingup.homework.service.HwSsatWordService;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.homework.util.ConstUtil.*;

/**
 * @author jun 2018/11/12.
 */
@Controller
@RequestMapping("/ssat")
public class SsatController {
    @Autowired
    private HwSsatWordService hwSsatWordService;

    @Autowired
    private HwSsatWordRecordService hwSsatWordRecordService;

    @Autowired
    private HwHomeworkRecordsService hwHomeworkRecordsService;

    @RequestMapping(value = "/list_by_paper_id.do", method = RequestMethod.POST)
    public void listByPaperId(@RequestParam(PARAM_PAPER_ID) Integer paperId,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        HttpResContent<List<JSONObject>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取SSAT套题数据");
        try {
            // check.
            checkParam(PARAM_PAPER_ID, paperId);
            // do.
            List<JSONObject> retList = getResultData(paperId);
            // response.
            saveSuccessMsgAndData(hrc, retList);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/save_answer.do", method = RequestMethod.POST)
    public void saveAnswer(@RequestParam(PARAM_PAPER_ID) Integer paperId,
                           @RequestParam(PARAM_ANSWER_DATA) String answerData,
                           @RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                           @RequestParam(PARAM_HOMEWORK_QUESTION_NUM) Integer homeworkQuestionNum,
                           HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存答案");
        try {
            // check.
            checkParam(PARAM_PAPER_ID, paperId);
            checkParam(PARAM_ANSWER_DATA, answerData);
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            checkParam(PARAM_HOMEWORK_QUESTION_NUM, homeworkQuestionNum);
            // do.
            JSONArray answerArr = JSON.parseArray(answerData);
            Integer total = answerArr.size();
            Integer correct = 0;
            for (int i = 0; i < answerArr.size(); i++) {
                JSONObject item = answerArr.getJSONObject(i);
                if (item.getString("rightAnswer").trim().equalsIgnoreCase(item.getString("studentAnswer").trim())) {
                    correct++;
                }
            }
            String userId = RedisUtils.getInstance().getUserId(request);
            HwSsatWordRecordDO tsSSatWordRecord = hwSsatWordRecordService.getByHomeworkInfo(userId, homeworkRecordId, homeworkQuestionNum);
            String statResult = String.format("%s/%s", correct, total);
            if (tsSSatWordRecord == null) {
                tsSSatWordRecord = new HwSsatWordRecordDO();
                tsSSatWordRecord.setAnswerData(answerArr);
                tsSSatWordRecord.setUserId(userId);
                tsSSatWordRecord.setPaperId(paperId);
                tsSSatWordRecord.setStatResult(statResult);
                tsSSatWordRecord.setCorrectNum(correct);
                tsSSatWordRecord.setTotalNum(total);
                tsSSatWordRecord.setHomeworkQuestionNum(homeworkQuestionNum);
                tsSSatWordRecord.setHomeworkRecordId(homeworkRecordId);
                if (!hwSsatWordRecordService.add(tsSSatWordRecord)) {
                    throw new Exception("保存答案失败");
                }
            } else {
                if (!hwSsatWordRecordService.updateAnswerData(tsSSatWordRecord.getId(), statResult, correct, total, answerArr)) {
                    throw new Exception("更新单词练习答案失败");
                }
            }
            hwHomeworkRecordsService.saveHomeworkProgress(homeworkRecordId, homeworkQuestionNum,null, null, null, null);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_ssat_record.do", method = RequestMethod.POST)
    public void getSsatRecord(@RequestParam(PARAM_PAPER_ID) Integer paperId,
                              @RequestParam(PARAM_USER_ID) String userId,
                              @RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                              @RequestParam(PARAM_HOMEWORK_QUESTION_NUM) Integer homeworkQuestionNum,
                              HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取SSAT记录");
        try {
            // check.
            checkParam(PARAM_PAPER_ID, paperId);
            checkParam(PARAM_USER_ID, userId);
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            checkParam(PARAM_HOMEWORK_QUESTION_NUM, homeworkQuestionNum);
            // do.

            JSONObject retObj = new JSONObject();
            HwSsatWordRecordDO tsSSatWordRecord = hwSsatWordRecordService.getByHomeworkInfo(userId, homeworkRecordId, homeworkQuestionNum);
            if (tsSSatWordRecord == null) {
                throw new Exception("用户记录不存在");
            }
            retObj.put(KEY_USER_RECORD, tsSSatWordRecord);
            retObj.put(KEY_SSAT_DATA, getResultData(paperId));
            // response.
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_student_ssat_record.do", method = RequestMethod.POST)
    public void getStudentSsatRecord(@RequestParam(PARAM_PAPER_ID) Integer paperId,
                                     @RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                     @RequestParam(PARAM_HOMEWORK_QUESTION_NUM) Integer homeworkQuestionNum,
                                     HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生SSAT记录");
        try {
            // check.
            checkParam(PARAM_PAPER_ID, paperId);
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            checkParam(PARAM_HOMEWORK_QUESTION_NUM, homeworkQuestionNum);
            // do.

            JSONObject retObj = new JSONObject();
            String userId = RedisUtils.getInstance().getUserId(request);
            HwSsatWordRecordDO tsSSatWordRecord = hwSsatWordRecordService.getByHomeworkInfo(userId, homeworkRecordId, homeworkQuestionNum);
            if (tsSSatWordRecord == null) {
                throw new Exception("用户记录不存在");
            }
            retObj.put(KEY_USER_RECORD, tsSSatWordRecord);
            retObj.put(KEY_SSAT_DATA, getResultData(paperId));
            // response.
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    private List<JSONObject> getResultData(Integer paperId) throws Exception {
        List<HwSsatWordDO> hwSsatWordList = hwSsatWordService.listByPaperId(paperId);
        List<JSONObject> retList = BJsonUtil.parseArray(hwSsatWordList, JSONObject.class);
        String[] arr = {"a", "b", "c", "d", "e"};
        for (JSONObject j : retList) {
            JSONObject option = new JSONObject();
            JSONObject translate = new JSONObject();
            for (String s : arr) {
                option.put(s.toLowerCase(), j.getString(KEY_OPTION + s.toUpperCase()));
                translate.put(s.toLowerCase(), j.getString(KEY_TRANSLATE + s.toUpperCase()));
                j.remove(KEY_OPTION + s.toUpperCase());
                j.remove(KEY_TRANSLATE + s.toUpperCase());
            }
            j.put(KEY_OPTION, option);
            j.put(KEY_TRANSLATE, translate);
        }
        return retList;
    }

}
